package com.hue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.entity.Orders;
import com.hue.entity.SeckillOrder;
import com.hue.entity.User;
import com.hue.entity.vo.GoodsVo;
import com.hue.service.GoodsService;
import com.hue.service.OrdersService;
import com.hue.service.SeckillOrderService;
import com.hue.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("seckill")
public class SeckillController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private RedisUtils redisUtils;

    /*

        优化前：
            QPS：100个线程:115  1000个线程：3.1
     */
    @GetMapping("/doSeckill")
    public String doSeckill(Integer goodsId, Model model, @CookieValue("token") String token) {
        GoodsVo goods = goodsService.getGoodsById(goodsId);
        //判断是否还有库存
        if (goods.getStockCount() < 1) {
            model.addAttribute("error", "已经被抢光啦！");
            return "secKillFail";
        }
        //判断用户是否重复抢购
        User user = redisUtils.getUser(token);
        QueryWrapper<SeckillOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", user.getMobile());
        SeckillOrder seckillOrder = seckillOrderService.getOne(wrapper);
        if (seckillOrder != null) {
            model.addAttribute("error", "你已经购买过啦！");
            return "secKillFail";
        }
        //生成订单
        Orders orders = ordersService.createOrder(user, goods);
        //生成秒杀订单
        seckillOrderService.createOrder(orders);
        model.addAttribute("orders", orders);
        model.addAttribute("goods", goods);
        return "orderDetail";
    }
}
